package Chess;

import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import Chess.chessPiece;
import Chess.chessType;
import Draw.blackBishop;
import Draw.blackKing;
import Draw.blackKnight;
import Draw.blackQueen;
import Draw.blackRook;
import Draw.blackpawn;
import Draw.whiteBishop;
import Draw.whiteKing;
import Draw.whiteKnight;
import Draw.whiteQueen;
import Draw.whiteRook;
import Draw.whitepawn;
import Chess.MoveStrategy;
import Chat.ChessChat;
import Chess.BorderPane;

public class Controller implements EventHandler<MouseEvent>{
    private static BorderPane borderPane;
    public static int[][] chess = new int[8][8];
    public static int x;
    public static int y;
    public static Image image = null;
    public static ImageView images=null;
    public static chessPiece currentPiece;
    public static chessPiece nextPiece;
    public static int backchessx = -1;
    public static int backchessy = -1;
    
	public Controller(BorderPane pane) {
        this.borderPane = pane;
    }
    

    @Override
    public void handle(MouseEvent event) {

        refresh();      
        //获取鼠标单击坐标，转化为格子的坐标
         x = (int)(event.getX()/borderPane.getCellLen());
         y = (int)(event.getY()/borderPane.getCellLen());

        //点击位置超出了棋盘的范围，不进行响应
        if(x>7||y>7)
            return ;

        //如果没有选中棋子，进行棋子选择
        if(isSelected()==null){
            chessPiece piece = isEmpty(x,y);
            //该座标无棋子
            if(piece==null)
                return;
            //将该棋子设为选中
            piece.setSelected(true);
            piece.getImageView().setSmooth(true);
            setMark(x,y,getPiece(x,y));
            
        }
        //否则进行移动，或重选需要的移动棋子
        else{        	
            currentPiece = isSelected();
            chessPiece newPiece = isEmpty(x,y);           
            //持方没有重选棋子，进行移动判断
            if(newPiece==null){
                //点击坐标的棋子           	
                nextPiece = getPiece(x,y);                
                //使用移动策略进行移动或吃子
                MoveStrategy moveStrategy = currentPiece.getMoveStrategy();
                backchessx = currentPiece.getX();
                backchessy = currentPiece.getY();
                Main.back.setDisable(false);
                
                if(Main.getj()==true){
                Compile compile = new Compile();
                compile.read(currentPiece, currentPiece.getX(), currentPiece.getY(), x, y);
                }
                
                //如果成功吃子或者移动，则更换持方
                if(moveStrategy.move(currentPiece,chess,x,y)){
                	 ChessChat chat = new ChessChat();
                     chat.chat(currentPiece, x, y);
                	//填充颜色
                	 for (int i=0;i<8;i++)
                         for(int j=0;j<8;j++) {
                             if((i+j)%2==0)
                                 BorderPane.gc.setFill(BorderPane.b);
                             else
                            	 BorderPane.gc.setFill(BorderPane.a);
                             BorderPane.gc.fillRect(i*90,j*90,90,90);
                         }
                	//如果成功吃子或者移动，则更换持方
                    if(borderPane.getCurrentSide().equals("W")){
                    	Main.a = 60;
                        borderPane.setCurrentSide("B");                       
                        ChessCurrent current = new ChessCurrent();
                    	current.current(borderPane.getCurrentSide());
                    }
                    else{
                    	Main.a = 60;
                    	borderPane.setCurrentSide("W");
                    	ChessCurrent current = new ChessCurrent();
                    	current.current(borderPane.getCurrentSide());
                    }      
                    //如果是吃子，则nextPiece存在，需要将其移出棋子列表，并去除其图像
                    if(nextPiece!=null){
                        isGameOver(nextPiece);
                        remove(nextPiece);
                    }
                }
            }
            //重选了棋子
            else{
            	 for (int i=0;i<8;i++)
                     for(int j=0;j<8;j++) {
                         if((i+j)%2==0)
                             BorderPane.gc.setFill(BorderPane.b);
                         else
                        	 BorderPane.gc.setFill(BorderPane.a);
                         BorderPane.gc.fillRect(i*90,j*90,90,90);
                     }
                currentPiece.setSelected(false);
                newPiece.setSelected(true);
                setMark(x,y,getPiece(x,y));
            }
        }
    }

    /**
     * 持放是否已经选择了一个棋子
     * 如果当前持放是白方，返回白方是否选中了一个需要进行移动的棋子
     * @return 返回被选中的棋子，如果没有则返回null
     */
	public chessPiece isSelected(){
        if(borderPane.getCurrentSide().equals("W")){
            for(int i=0;i<borderPane.getWhiteChessList().size();i++){
                chessPiece piece = (chessPiece) borderPane.getWhiteChessList().get(i);
                if(piece.isSelected()){                	
                    return piece;
                    }
            }
        }
        else{
            for(int i=0;i<borderPane.getBlackChessList().size();i++){
                chessPiece piece = (chessPiece) borderPane.getBlackChessList().get(i);
                if(piece.isSelected())
                    return piece;
            }
        }
        return null;
    }

    /**
     * 返回当前持放在x，y的棋子
     * @param x
     * @param y
     * @return
     */
	public chessPiece isEmpty(int x, int y){
        //如果当前持放是白方，返回该座标是否有白方棋子
       if(borderPane.getCurrentSide().equals("W")){
           for(int i=0;i<borderPane.getWhiteChessList().size();i++){
               chessPiece piece = (chessPiece) borderPane.getWhiteChessList().get(i);
               if(piece.getX()==x && piece.getY()==y)
                   return piece;
           }
       }
       //如果当前持放是黑方，返回该座标是否有黑方棋子
       else{
           for(int i=0;i<borderPane.getBlackChessList().size();i++){
               chessPiece piece = (chessPiece) borderPane.getBlackChessList().get(i);
               if(piece.getX()==x && piece.getY()==y)
                   return piece;
           }
       }
       return null;
    }

    /**
     * 获得棋盘上坐标x，y上的棋子，如果不存在棋子，则返回null
     * @param x
     * @param y
     * @return
     */
	public static chessPiece getPiece(int x, int y){
        for(int i=0;i<borderPane.getWhiteChessList().size();i++){
            chessPiece piece = (chessPiece) borderPane.getWhiteChessList().get(i);
            if(piece.getX()==x && piece.getY()==y)
                return piece;
        }
        for(int i=0;i<borderPane.getBlackChessList().size();i++){
            chessPiece piece = (chessPiece) borderPane.getBlackChessList().get(i);
            if(piece.getX()==x && piece.getY()==y)
                return piece;
        }
        return null;
    }

	public void remove(chessPiece piece){
        piece.getImageView().setImage(null);
        if(borderPane.getCurrentSide().equals("B")){
            for(int i=0;i<borderPane.getBlackChessList().size();i++){
                chessPiece piece1 = (chessPiece) borderPane.getBlackChessList().get(i);
                if(piece.equals(piece1)){
                    borderPane.getBlackChessList().remove(i);
                    break;
                }
            }
        }
        else{
            for(int i=0;i<borderPane.getWhiteChessList().size();i++){
                chessPiece piece1 = (chessPiece) borderPane.getWhiteChessList().get(i);
                if(piece.equals(piece1)){
                    borderPane.getWhiteChessList().remove(i);
                    break;
                }
            }
        }
    }

    //更新棋盘数组
	public static void refresh(){
        //初始化棋盘数组
        for(int i=0;i<8;i++)
            for(int j=0;j<8;j++){
                chess[i][j] = 0;
            }
        for(int i=0;i<borderPane.getWhiteChessList().size();i++){
            chessPiece piece = (chessPiece) borderPane.getWhiteChessList().get(i);
            chess[piece.getY()][piece.getX()] = 1;
        }
        for(int i=0;i<borderPane.getBlackChessList().size();i++){
            chessPiece piece = (chessPiece) borderPane.getBlackChessList().get(i);
            chess[piece.getY()][piece.getX()] = 2;
        }
    }
    
    public void setMark(int x,int y,chessPiece piece){    	
    	if(piece.getChessType()==chessType.whitePawn){
    		Draw.whitepawn pawn = new whitepawn();
    		pawn.whitepawn(x,y,chess);
    	}
    	else if(piece.getChessType()==chessType.blackPawn){
    		Draw.blackpawn pawn = new blackpawn();
    		pawn.blackpawn(x,y,chess);
    	}
    	else if(piece.getChessType()==chessType.blackRook){
    		Draw.blackRook rook = new blackRook();
    		rook.blackrook(x, y,chess);
    	}
    	else if(piece.getChessType()==chessType.whiteRook){
    		Draw.whiteRook rook = new whiteRook();
    		rook.whiterook(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.whiteKnight){
    		Draw.whiteKnight knight = new whiteKnight();
    		knight.whiteKnight(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.blackKnight){
    		Draw.blackKnight knight = new blackKnight();
    		knight.blackKnight(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.whiteBishop){
    		Draw.whiteBishop bishop = new whiteBishop();
    		bishop.whitebishop(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.blackBishop){
    		Draw.blackBishop bishop = new blackBishop();
    		bishop.blackbishop(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.whiteKing){
    		Draw.whiteKing king = new whiteKing();
    		king.whiteking(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.blackKing){
    		Draw.blackKing king = new blackKing();
    		king.blackking(x,y,chess);
    	}
    	else if(piece.getChessType()==chessType.whiteQueen){
    		Draw.whiteQueen queen = new whiteQueen();
    		queen.whitequeen(x, y, chess);
    	}
    	else if(piece.getChessType()==chessType.blackQueen){
    		Draw.blackQueen queen = new blackQueen();
    		queen.blackqueen(x, y, chess);
    	}
    }

    //判断游戏是否结束
    public void isGameOver(chessPiece piece){
        if(piece.getChessType().equals(chessType.blackKing) || piece.getChessType().equals(chessType.whiteKing )){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("游戏结束！！");
            String content = borderPane.getCurrentSide().equals("W")? "获胜者为黑方！！！":"获胜者为白方！！！";
            alert.setContentText(content);
            alert.show();
           
        }
    }
}
